﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using YAF.Core;
using System.Web.Security;
using YAF.Utils;
using YAF.Providers.Membership;
using YAF.Classes.Data;

/// <summary>
/// Summary description for Company
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Company : System.Web.Services.WebService
{

    public Company()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string SaveSignups(object values)
    {
        Dictionary<string, object> dic = values as Dictionary<string, object>;

        SqlParameter[] pars = new SqlParameter[20];
        pars[0] = new SqlParameter("name", dic["companyName"]);
        pars[0].DbType = System.Data.DbType.String;
        pars[1] = new SqlParameter("country_id", dic["country"]);
        pars[1].DbType = System.Data.DbType.Int64;
        pars[2] = new SqlParameter("city", dic["city"]);
        pars[2].DbType = System.Data.DbType.String;
        pars[3] = new SqlParameter("postcode", dic["postCode"]);
        pars[3].DbType = System.Data.DbType.String;
        pars[4] = new SqlParameter("address", dic["address"]);
        pars[4].DbType = System.Data.DbType.String;
        pars[5] = new SqlParameter("type_company_id", dic["companyType"]);
        pars[5].DbType = System.Data.DbType.Int64;
        pars[6] = new SqlParameter("operating_licence", "");
        pars[6].DbType = System.Data.DbType.String;
        pars[7] = new SqlParameter("operating_activity", dic["opActivityInfo"]);
        pars[7].DbType = System.Data.DbType.String;
        pars[8] = new SqlParameter("telephone", dic["telephone"]);
        pars[8].DbType = System.Data.DbType.String;
        pars[9] = new SqlParameter("ext", dic["ext"]);
        pars[9].DbType = System.Data.DbType.String;
        pars[10] = new SqlParameter("fax", dic["fax"]);
        pars[10].DbType = System.Data.DbType.String;
        pars[11] = new SqlParameter("mobile", dic["mobile"]);
        pars[11].DbType = System.Data.DbType.String;
        pars[12] = new SqlParameter("website", dic["website"]);
        pars[12].DbType = System.Data.DbType.String;
        pars[13] = new SqlParameter("contact_person", dic["contactPerson"]);
        pars[13].DbType = System.Data.DbType.String;
        Dictionary<int, int> _langs = dic["languages"] as Dictionary<int, int>;
        IEnumerator len = ((object[])dic["languages"]).GetEnumerator();
        string langs = "";
        while (len.MoveNext())
        {
            langs += len.Current+",";
        }
        pars[14] = new SqlParameter("language", langs);
        pars[14].DbType = System.Data.DbType.String;
        pars[15] = new SqlParameter("job_title", dic["JobTitle"]);
        pars[15].DbType = System.Data.DbType.String;
        pars[16] = new SqlParameter("company_status", 0);//TBD
        pars[16].DbType = System.Data.DbType.Int16;
        pars[16].Value = 0;
        pars[17] = new SqlParameter("email", dic["email"]);
        pars[17].DbType = System.Data.DbType.String;
        pars[18] = new SqlParameter("mobile_phone", dic["mobile"]);
        pars[18].DbType = System.Data.DbType.String;
        pars[19] = new SqlParameter("tax_file_number", dic["taxFileNumber"]);
        pars[19].DbType = System.Data.DbType.String;

        string msg = "";

        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_InsCompany", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                foreach (SqlParameter p in pars)
                    cmd.Parameters.Add(p);
                int val = 0;
                try
                {
                    Int32.TryParse(cmd.ExecuteScalar().ToString(), out val);
                }
                catch (Exception ex)
                {
                    msg = ex.ToString();
                }
                string username = dic["email"].ToString();
                string pass = DAO.CodeFactory.GetUniqueKey(8);
                if (val > 0)
                {
                    //insert user
                    cmd.Parameters.Clear();
                    cmd.CommandText = "SP_InsUser";
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("name", dic["companyName"]));
                    cmd.Parameters.Add(new SqlParameter("username", username));
                    cmd.Parameters.Add(new SqlParameter("password", DAO.CodeFactory.CalcMD5String(pass)));
                    cmd.Parameters.Add(new SqlParameter("isActive", "true"));
                    cmd.Parameters.Add(new SqlParameter("userType", "normal"));
                    cmd.Parameters.Add(new SqlParameter("company_id", val));
                    cmd.Parameters.Add(new SqlParameter("orig_pass", pass));

                    int userid = 0;
                    try
                    {
                        Int32.TryParse(cmd.ExecuteScalar().ToString(), out userid);
                    }
                    catch (Exception ex)
                    {
                        msg = ex.ToString();
                    }
                    if (userid > 0)
                    {
                        Dictionary<int, int> trans = dic["typeofTransportActivity"] as Dictionary<int, int>;
                        IEnumerator en = ((object[])dic["typeofTransportActivity"]).GetEnumerator();
                        while (en.MoveNext())
                        {
                            cmd.Parameters.Clear();
                            cmd.CommandText = "SP_InsCJCompanyTransport";
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.Add(new SqlParameter("company_id", val));
                            cmd.Parameters.Add(new SqlParameter("transporttype_id", en.Current));
                            int cj = 0;
                            try
                            {
                                Int32.TryParse(cmd.ExecuteScalar().ToString(), out cj);
                            }
                            catch (Exception ex)
                            {
                                msg = ex.ToString();
                            }
                        }
                    }
                }
                int langid = DAO.Connection.DEFAULT_LANGUAGE;
                /*if (Session["language"] != null)
                {
                    if (!Int32.TryParse(Session["language"].ToString(), out langid))
                        langid = DAO.Connection.DEFAULT_LANGUAGE;
                }
                else langid = DAO.Connection.DEFAULT_LANGUAGE;
                */
                if (msg != "")
                    return "{\"status\":\"0\",\"msg':\"" + msg + "\"}";//nosuccRegistration
                else
                {
                    SendEmail(dic);
                    CreateUserForForum(username, pass);
                    return "{\"status\":\"1\",\"msg\":\"" + DAO.TextBaseFactory.loadText("successRegistration", langid) + ", "
                        + DAO.TextBaseFactory.loadInfoText("successRegistrationM", langid) + "\"}";
                }
            }
        }
        
    }

    private void CreateUserForForum(string username, string pass)
    {
        try
        {
            string hashinput = DateTime.UtcNow + pass + Security.CreatePassword(20);
            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5");

            MembershipCreateStatus status;
            MembershipUser user = Membership.CreateUser(
                username,
                pass.Trim(),
                username,
                "test",
                "test",
                true,
                null,
                out status);

            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, username);
            RoleMembershipHelper.AddUserToRole(username, "Registered");
            int? userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);
            YafUserProfile userProfile = YafUserProfile.GetProfile(username);
            userProfile.Save();
        }
        catch (Exception ex)
        {
            string errorInfo =
           "<br>Username: " + username +
           "<br>Password: " + pass +
           "<br>Source: " + ex.Source +
           "<br>Message: " + ex.Message +
           "<br>Stack trace: " + ex.StackTrace;
            errorInfo += (ex.InnerException != null) ? ex.InnerException.Message : "";
            string senderMailAdress = ConfigurationManager.AppSettings["senderMailAdress"].ToString();
            string host = ConfigurationManager.AppSettings["host"].ToString();
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

            //create mail message body
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            mail.IsBodyHtml = true;
            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.Body = errorInfo;
            mail.To.Add(new System.Net.Mail.MailAddress("ratkop@gmail.com"));
            mail.Bcc.Add("info@transportexchange.org");
            mail.From = new System.Net.Mail.MailAddress(senderMailAdress);
            mail.Subject = "TransportExchange.org Forum User Creation";

            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

            //set SmtpClient properties
            smtpClient.Port = 25;
            smtpClient.Host = "173.192.111.22";

            string uname = ConfigurationManager.AppSettings["username"].ToString();
            string pswd = ConfigurationManager.AppSettings["password"].ToString();
            smtpClient.Credentials = new System.Net.NetworkCredential(uname, pswd);
            try
            {
                smtpClient.Send(mail);
            }
            catch { }
        }
        //LegacyDb.user_save(
        //    UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey),
        //    YafContext.Current.PageBoardID,
        //    null,
        //    null,
        //    null,
        //    TimeZone.CurrentTimeZone.ToType<int>(),
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null,
        //    null);
        
        /*string strHash = FormsAuthentication.HashPasswordForStoringInConfigFile(pass, "SHA1");
        object app = "YetAnotherForum";
        object objUserKey = YAF.Providers.Profile.DB.Current.GetProviderUserKey(app, (object)username);
        YAF.Providers.Membership.DB.Current.CreateUser(app,username,pass, "", 
        YAF.Providers.Membership.DB.Current.CreateUser(app, username, strHash, "", 0, username, "", "", true, objUserKey);
YAF.Providers.Roles.DB.AddUserToRole(strAppName, strUsername, "Registered")
        string guestUserName = UserMembershipHelper.GuestUserName;
        guestUserName = (guestUserName != null && guestUserName != "") ? guestUserName.ToLower() : String.Empty;

        RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, username);
         * */
    }

    private void SendEmail(Dictionary<string, object> dic)
    {
        //get mail settings
        string senderMailAdress = ConfigurationManager.AppSettings["senderMailAdress"].ToString();
        string host = ConfigurationManager.AppSettings["host"].ToString();
        //string username = ConfigurationManager.AppSettings["username"].ToString();
        //string password = ConfigurationManager.AppSettings["password"].ToString();

        //create new mail message
        MailMessage mail = new MailMessage();

        //create mail message body
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        mail.IsBodyHtml = true;
        mail.BodyEncoding = System.Text.Encoding.UTF8;

        sb.Append("<html><head>");
        sb.Append("<style> body{font-family: \"Calibri\",\"sans-serif\";font-size: 11pt;margin: 0 0 0.0001pt;}</style>");
        sb.Append("</head><body>");

        sb.Append("<center><span style='font-size:16px'><b>WELCOME TO TRANSPORT EXCHANGE<b></span></center>");
        sb.Append("<b>www.TransportExchange.org</b>");
        sb.Append("<br><br>");
        sb.Append("Thank you for taking the time to register. ");
        sb.Append("<br>");
        sb.Append("<p>We are pleased to advise you that <b>your registration is under review.</b></p>");
        sb.Append("<p>Your status is: NOT ACTIVE</p>");
        sb.Append("<p>Bellow is the information that you have provided. If the information is incorrect, please contact our Administrator and provide us with the new information on support@transportexchange.org.</p>");
        sb.Append("<p>Member Type: Bronze Member</p>");
        sb.Append("<p>COMPANY INFORMATION:</p>");
        sb.Append("<strong>Company name:</strong> " + dic["companyName"] + "<br>");
        sb.Append("<strong>Country:</strong> " + dic["country"] + "<br>");
        sb.Append("<strong>City:</strong> " + dic["city"] + "<br>");
        sb.Append("<strong>Post code:</strong> " + dic["postCode"] + "<br>");
        sb.Append("<strong>Address:</strong> " + dic["address"] + "<br>");

        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_GetUniversalTypeById(@id, @language_id)", conn))
            {
                cmd.Parameters.AddWithValue("id", dic["companyType"]);
                cmd.Parameters.AddWithValue("language_id", 1);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    sb.Append("<strong>Type of Company:</strong> " + dr["name"] + "<br>");
                }
                dr.Close();
            }
        }
        Dictionary<int, int> trans = dic["typeofTransportActivity"] as Dictionary<int, int>;
        IEnumerator en = ((object[])dic["typeofTransportActivity"]).GetEnumerator();
        sb.Append("<strong>Type of transport:</strong>");
        while (en.MoveNext())
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT name FROM Fn_GetUniversalTypeById(@id, @language_id)", conn))
                {
                    cmd.Parameters.AddWithValue("id", en.Current);
                    cmd.Parameters.AddWithValue("language_id", 1);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        sb.Append(" " + dr["name"]);
                    }
                    dr.Close();
                }
            }
        }
        sb.Append("<br><strong>Operating Activity Information:</strong> " + dic["opActivityInfo"] + "<br>");

        sb.Append("<p>CONTACT DETAILS:</p>");
        sb.Append("<strong>Telephone:</strong> " + dic["telephone"] + "<br>");
        sb.Append("<strong>Fax:</strong> " + dic["fax"] + "<br>");
        sb.Append("<strong>Mobile:</strong> " + dic["mobile"] + "<br>");
        sb.Append("<strong>Website:</strong> " + dic["website"] + "<br>");
        sb.Append("<strong>Contact person:</strong> " + dic["contactPerson"] + "<br>");
        Dictionary<int, int> _langs = dic["languages"] as Dictionary<int, int>;
        IEnumerator len = ((object[])dic["languages"]).GetEnumerator();
        
        sb.Append("<strong>Language(s):</strong><br>");
        while (len.MoveNext())
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT name FROM Fn_GetPlace(@id)", conn))
                {
                    cmd.Parameters.AddWithValue("id", len.Current);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        sb.Append(" " + dr["name"]);
                    }
                    dr.Close();
                }
            }
        }
        sb.Append("<strong>Job Title:</strong> " + dic["JobTitle"] + "<br>");

        sb.Append("<p>In order for us to process your registration, we need you to submit via fax or email the following documents:</p>");
        sb.Append("<p>• Copy of your company’s operating license (if applicable), or a document for registration of legal entity for your company.</p>");
        sb.Append("<p>We need these documents in order for us to establish whether you are a legitimate, registered business. This safety feature ensures that all our clients, including you, are protected from fraudulent companies or spammers. We will NEVER disclose these documents to Third Parties, and we will securely store them in our system only for the duration of your membership.</p>");
        sb.Append("<br>");
        sb.Append("<p>Once we receive your documents, we will notify you within 24 hours on the outcome of your application.</p>");
        sb.Append("<p>Thank you for your interest in becoming a member. </p>");
        sb.Append("<br><br>");
        sb.Append("<p style='font-size:16px'><b>Transport Exchange</b></p>");
        sb.Append("<p>Str. 710 No. 1 1000 Skopje - Macedonia</p>");
        sb.Append("<p>Tel +389 2 2551 057 </p>");
        sb.Append("<p>Fax +389 2 2549 016 </p>");
        sb.Append("<p>Cell. Tel. +389 78399019 </p>");
        sb.Append("<p>e-mail: <a href='mailto:info@transportexchange.org'>info@transportexchange.org</a> </p>");
        sb.Append("<p>skype: transportexchange</p>");
        sb.Append("<p>Website: <a href='http://www.transportexchange.org'>www.transportexchange.org</a></p>");
        sb.Append("</body></html>");
        mail.Body = sb.ToString();

        //set mail message properties
        mail.To.Add(new MailAddress((string)dic["email"]));
        mail.Bcc.Add("info@transportexchange.org");
        mail.From = new MailAddress(senderMailAdress);
        mail.Subject = "TransportExchange.org Registration";

        //create new SmtpClient
        SmtpClient smtpClient = new SmtpClient();

        //set SmtpClient properties
        smtpClient.Port = 25;
        smtpClient.Host = "173.192.111.22";
        // for example gmail smtp server
        //smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
        string username = ConfigurationManager.AppSettings["username"].ToString();
        string password = ConfigurationManager.AppSettings["password"].ToString();
        smtpClient.Credentials = new System.Net.NetworkCredential(username, password);


        //send mail message
        try
        {
            smtpClient.Send(mail);
            mail = new MailMessage();
            mail.Body = sb.ToString();

            //set mail message properties
            mail.To.Add("info@transportexchange.org");
            mail.From = new MailAddress(senderMailAdress);
            mail.Subject = "TransportExchange.org Registration";
            smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
            try
            {
                smtpClient.Send(mail);
            }
            catch { }
        }
        catch (Exception ex)
        {
        }
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string ValidateEmail(string email)
    {
        if (email != "")
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_GetUserByEmail(@email)", conn))
                {
                    cmd.Parameters.Add("email", email);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        return "{\"status\":\"1\"}";
                    }
                    dr.Close();
                }
            }
        }
        return "{\"status\":\"0\"}";;
    }
}

